package cn.b.sky.user.service.impl;

import cn.b.sky.common.utils.FTPUtils;
import cn.b.sky.user.dao.AttachmentDao;
import cn.b.sky.user.model.Attachment;
import cn.b.sky.user.service.AttachmentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service("attachmentService")
public class AttachmentServiceImpl implements AttachmentService {

  @Resource
  AttachmentDao attachmentDao;
  
  @Autowired
  FTPUtils ftpUtils;

  @Override
  public Attachment selectAttachmentByHashCode(String siteCode, String hashCode) {
    return attachmentDao.selectAttachmentByHashCode(siteCode, hashCode);
  }

  @Override
  public Attachment selectAttachmentByAttachmentCode(String siteCode, String attachmentCode) {
    return attachmentDao.selectAttachmentByAttachmentCode(siteCode, attachmentCode);
  }

  @Override
  public void updateAttachmentRefCount(Attachment attachment) {
    attachmentDao.updateAttachmentRefCount(attachment);

  }

  @Override
  public void deleteAttachment(String siteCode, String attachmentCode) {
    if(!StringUtils.isBlank(attachmentCode) && StringUtils.isBlank(siteCode)){
      Attachment att = this.selectAttachmentByAttachmentCode(siteCode, attachmentCode);
      if(att != null){
        if(att.getRefCount() > 1){
          //更新索引
          att.setRefCount(att.getRefCount() -1);
          this.updateAttachmentRefCount(att);
        }else{
          attachmentDao.deleteAttachment(siteCode, attachmentCode);
          ftpUtils.deleteFile(att.getSavePath());
        }
      }
    }

  }

  @Override
  public void insertAttachment(Attachment attachment) {
    attachmentDao.insertAttachment(attachment);
  }

  @Override
  public void checkIsExtisAttachment(Attachment attachMent, String md5) {
    if(attachMent!=null && !StringUtils.isBlank(attachMent.getSiteCode())){
      Attachment att = this.selectAttachmentByHashCode(attachMent.getSiteCode(), md5);
      if(att != null){
        //更新索引
        att.setRefCount(att.getRefCount() + 1);
        this.updateAttachmentRefCount(att);
        //赋值
        attachMent.setAttachmentCode(att.getAttachmentCode());
        attachMent.setFileSize(att.getFileSize());
        attachMent.setSavePath(att.getSavePath());
      }
    }
  }

}
